import {express} from "express"
import {mongoose} from "mongoose"
import {user, User} from "user.model.js"
import {bcrypt} from "bcrypt"
import {jwt} from "jsonwebtoken"
import {auth} from "auth.middleware.js"


const router = express.Router()

router.get("/", auth, (req, res, next) => {
  User.find()
    .then( (result) => {
      res.status(200).json({
        userData: result,
      })
    } )
    .catch((err) => {
      console.log(err)
      res.status(500).json({
        error: err,
      })
    })
})

router.get("/:id", (req, res, next) => {
  console.log(req.params.id)
  User.findById(req.params.id).then((result) => {
    res.status(200)
      .json({
        user: result,
      })
      .catch((err) => {
        console.log(err)
        res.status(500).json({
          error: err,
        })
      })
  })
})

router.post("/", (req, res, next) => {
  bcrypt.hash(req.body.password, 10, (err, hash => {
    if (err) {
      return res.status(500).json({
        error: err,
      })
    } else {
      new User(req.body)
        .save()
        .then((result) => {
          console.log(result);
          res.status(200).json({
            newUser: result,
          })
        })
        .catch((err) => {
          console.log(err);
          res.status(500).json({
            error: err,
          })
        })
    }
  })
})


router.post("/login", (req, res, next) => {
  user.
    find({
      username: req.body.username,
    })
    .exec()
    .then((user) => {
      if (user.length < 1) {
        return res.status(401).json({
          msg: "user not found",
        })
      }

      bcrypt.compare(req.body.password, user[0].password, (err, result) => {
        if (!result) {
          return res.status(401).json({
            msg: "password match failed",
          })
        }

        if (result) {
          const token = jwt.sign(
            {
              username: user[0].username,
              userType: user[0].userType,
              email: user[0].email,
              phoneno: user[0].phoneno,
            },
            "this is dummy text",
            {
              // token time
              expiresIn: "24h"
            }
          )

          res.status(200).json(
            {
              username: user[0].username,
              userType: user[0].userType,
              email: user[0].email,
              phoneno: user[0].phoneno,
              token: token,
            }
          )
        }
      })
    })
    .catch((err) => {
      res.status(500).json({
        error: err
      })
    })
})

// delete is no need

// put is no need




export router
